package com.b2c.erp.controller.funds;

import com.b2c.entity.api.ApiResult;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.funds.OrderSettlementPddEntity;
import com.b2c.entity.pdd.PddMarketingFeeEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.ShopService;
import com.b2c.service.pdd.PddMarketingFeeService;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RequestMapping("/funds")
@Controller
public class MarketingCostsPddController {
    @Autowired
    private ShopService shopService;
    private static Logger log = LoggerFactory.getLogger(MarketingCostsPddController.class);
    @Autowired
    private PddMarketingFeeService marketingFeeService;

    @RequestMapping("/marketing_costs_list_pdd")
    public String orderSettlementList(Model model, HttpServletRequest request) {
        Integer pageIndex = 1, pageSize = 100;//DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }

        String startDate = "";
        if (StringUtils.hasText(request.getParameter("startDate")))
            startDate = request.getParameter("startDate");
        // else
        //     startDate = DateUtil.dateToString(DateUtil.beforeDayDate(30), "yyyy-MM-dd");
        model.addAttribute("startDate", startDate);
        String endDate = "";
        if (StringUtils.hasText(request.getParameter("endDate")))
            endDate = request.getParameter("endDate");
        // else
        //     endDate = DateUtil.getCurrentDate();
        model.addAttribute("endDate", endDate);


        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        // 有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId, 5);// type=5是拼多多
        model.addAttribute("shops", shops);
        model.addAttribute("shopId", 5);

        var result = marketingFeeService.getList(pageIndex,pageSize,5,1,startDate,endDate);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        model.addAttribute("pageTitle", "营销费用 - 拼多多");
        model.addAttribute("view", "marketing_costs_list_pdd");
        model.addAttribute("pView", "pd");
        return "funds/marketing_costs_list_pdd_list";
    }

    @RequestMapping("/marketing_costs_list_pdd_import")
    public String orderSettlementImport(Model model, HttpServletRequest request) {
        Integer userId = DataConfigObject.getInstance().getLoginUserId();
        // 有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId, 5);// type=5是拼多多
        model.addAttribute("shops", shops);
        model.addAttribute("shopId", 5);
        model.addAttribute("view", "marketing_costs_list_pdd");
        model.addAttribute("pView", "pd");
        return "funds/marketing_costs_list_pdd_import";
    }

    @ResponseBody
    @RequestMapping(value = "/marketing_costs_list_pdd_import_ajax", method = RequestMethod.POST)
    public ApiResult<List<PddMarketingFeeEntity>> orderSendExcel(@RequestParam("excel") MultipartFile file,
                                                                    HttpServletRequest req) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********导入pdd结算数据，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");
        InputStream fis = null;
        fis = new FileInputStream(destFileName);
        if (fis == null)
            return new ApiResult<>(502, "没有文件");

        Workbook workbook = null;

        try {
            if (fileName.toLowerCase().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(fis);
            } else if (fileName.toLowerCase().endsWith("xls")) {
                workbook = new HSSFWorkbook(fis);
            }
            // workbook = new HSSFWorkbook(fis);
        } catch (Exception ex) {
            log.info("/***********导入pdd结算数据***出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        if (workbook == null)
            return new ApiResult<>(502, "未读取到Excel文件");

        /**************** 开始处理批批网csv订单 ****************/
        // 订单list
        List<PddMarketingFeeEntity> list = new ArrayList<>();
        Sheet sheet = null;

        try {
            sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();// 最后一行索引
            Row row = null;

            for (int i = 1; i <= lastRowNum; i++) {
                try {
                    row = sheet.getRow(i);
                    if(row == null) continue;
                    String datetime = "";
                    Cell cell0 = row.getCell(0);
                    if (cell0 != null)
                        datetime = cell0.getStringCellValue();

                    log.info("/***********导入pdd营销费用数据**[" + i + "]**读取到日期:" + datetime + "***********/");

//                    orderSn = orderSn.replace("\t", "").trim();

                    PddMarketingFeeEntity r = new PddMarketingFeeEntity();
                    r.setId(Long.parseLong(i+""));
                    r.setDatetime(datetime);
//                    String settlementTime = "";
//                    Cell cell1 = row.getCell(1);
//                    if (cell1 == null)
//                        continue;
//                    if (HSSFDateUtil.isCellDateFormatted(cell1)) {// 日期类型
//                        // 短日期转化为字符串
//                        Date date = cell1.getDateCellValue();
//                        if (date != null) {
//                            // 标准0点 1970/01/01 08:00:00
//                            if (date.getTime() % 86400000 == 16 * 3600 * 1000
//                                    && cell1.getCellStyle().getDataFormat() == 14) {
//                                settlementTime = new SimpleDateFormat("yyyy-MM-dd").format(date);
//                            } else {
//                                settlementTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
//                            }
//                        }
//                    }

//                    r.setSettlementTime(settlementTime);
                    r.setZjtype(row.getCell(1).getStringCellValue());
                    String type = row.getCell(2).getStringCellValue();
                    if(type.equals("支出")) r.setType(1);
                    else if(type.equals("收入")) r.setType(2);
                    try {
                        r.setAmount(new BigDecimal(row.getCell(5).getStringCellValue()));
                    }catch (Exception ee) {
                        Double amount = row.getCell(5).getNumericCellValue();
                        r.setAmount(new BigDecimal(amount));
                    }
                    try {
                        r.setBalance(new BigDecimal(row.getCell(6).getStringCellValue()));
                    }catch (Exception ee1) {
                        Double balance = row.getCell(6).getNumericCellValue();
                        r.setBalance(new BigDecimal(balance));
                    }
                    String remark = row.getCell(7).getStringCellValue();
                    r.setRemark(remark);


                    list.add(r);
                } catch (Exception e) {
                    log.info("/***********读取pdd营销费用数据**读取数据异常[" + i + "]**" + e.getMessage() + "***********/");
                }
            }

        } catch (Exception ex) {
            log.info("/***********导入pdd营销费用数据****出现异常：" + ex.getMessage() + "***********/");
            return new ApiResult<>(500, ex.getMessage());
        }

        return new ApiResult<>(0, "SUCCESS", list);
    }

    @ResponseBody
    @RequestMapping(value = "/marketing_costs_list_pdd_import_submit", method = RequestMethod.POST)
    public ApiResult<String> orderExcelImportSubmit(@RequestBody MarketingCostPddImportSubmitReq req) {
        if (req.getShopId() == null || req.getShopId() == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有shopId");

        List<PddMarketingFeeEntity> orderList = req.getOrderList();
        if (orderList == null || orderList.size() == 0)
            return new ApiResult<>(EnumResultVo.ParamsError.getIndex(), "参数错误：没有orderList");

        Integer shopId = req.getShopId();


        ResultVo<String> resultVo = marketingFeeService.importExcelFeeList(orderList,shopId);

        if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
            return new ApiResult<>(0, "SUCCESS", resultVo.getData());
        } else return new ApiResult<>(resultVo.getCode(), resultVo.getMsg());
    }
}
